﻿/*******************************************************************************
 * AAEngine
 * Copyright (c) 2010 Mike Jarosch
 *
 * Original source Shawn Hargreaves:
 * Copyright (c) Shawn Hargreaves
 * http://blogs.msdn.com/shawnhar/archive/2007/06/08/displaying-the-framerate.aspx
 ******************************************************************************/

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using AAEngine.Engine;

namespace AAEngine.GameComponents
{
    /// <summary>
    /// Displays the number of frames rendered per second.
    /// </summary>
    public class FPSOverlay : DrawableGameComponent
    {
        /// <summary>
        /// The name of the font to use to draw the FPS counter.
        /// </summary>
        public string FontName { get; set; }
    
        public FPSOverlay(Game game)
            : base(game)
        {
            DrawOrder = Int32.MaxValue; // draw last
            FontName = "Fonts/SystemFont";
        }
    
        protected override void LoadContent()
        {
            _spriteBatch = new SpriteBatch(GraphicsDevice);
            _font = AAGame.EngineContent.Load<SpriteFont>(FontName);
        }
     
        public override void Update(GameTime gameTime)
        {
            _elapsed += (float)gameTime.ElapsedGameTime.TotalSeconds;
            if (_elapsed >= 1f)
            {
                _elapsed -= 1f;
                _frameRate = _frameCounter;
                _frameCounter = 0;
            }
        }
     
        public override void Draw(GameTime gameTime)
        {
            _frameCounter += 1;
            _spriteBatch.Begin(); // (SpriteBlendMode.AlphaBlend, SpriteSortMode.FrontToBack, SaveStateMode.None);
            _spriteBatch.DrawString(_font, _frameRate.ToString(), TextOffset, Color.White);
            _spriteBatch.End();
        }
    
        private SpriteFont _font;
        private SpriteBatch _spriteBatch;
    
        private float _elapsed;
        private int _frameCounter;
        private int _frameRate;
    
        private readonly Vector2 TextOffset = new Vector2(10, 10);
    }
}
